<template>
  <div>
    <!-- 搜索条件 -->
    <el-card v-show="showQueryForm" class="form-card">
      <QueryForm ref="queryFormRef" :form-data="queryFormData" :items="queryFormItems" :model="queryFormData" :show-control="true" label-width="82px">
        <QueryFormItem label="登录时间">
          <el-date-picker v-model="pickerDate"
                          :shortcuts="pickerShortcuts"
                          class="card-header-extra-action"
                          clearable
                          end-placeholder="结束日期"
                          format="YYYY-MM-DD"
                          start-placeholder="开始日期"
                          type="daterange"
                          value-format="YYYY-MM-DD"/>
        </QueryFormItem>

        <template #control>
          <el-button icon="Search" type="info" @click="handleSearch">{{ $t('form.search') }}</el-button>
          <el-button icon="Refresh" @click="handleResetQueryForm">{{ $t('form.reset') }}</el-button>
        </template>
      </QueryForm>
    </el-card>

    <!-- 列表数据 -->
    <el-card class="content-card">
      <!-- 工具栏 -->
      <table-toolbar v-model:columns="columns"
                     v-model:show-query-form="showQueryForm"
                     v-model:size="size"
                     v-model:stripe="stripe"
                     @refresh="handleSearch">
      </table-toolbar>

      <!-- 列表记录 -->
      <div class="table-wrapper">
        <!-- 列表数据 -->
        <el-table ref="tableRef"
                  v-loading="loading"
                  :data="tableData"
                  :size="size"
                  :stripe="stripe"
                  row-key="id"
                  show-overflow-tooltip
                  @select="handleSelectChange"
                  @select-all="handleSelectAll"
                  @sort-change="handleSortChange">
          <template #empty>
            <el-empty class="table-empty" description="暂无数据"/>
          </template>

          <table-column :columns="columns">
            <template #user_id="scope">
              <UserInfoLink :user-id="scope.row.user_id"/>
            </template>
          </table-column>
        </el-table>

        <!-- 分页操作 -->
        <el-pagination v-if="totalCount > 0"
                       :current-page="pageQuery.pageNum"
                       :page-size="pageQuery.pageSize"
                       :page-sizes="pageSizes"
                       :total="totalCount"
                       background
                       class="table-pagination"
                       layout="total, sizes, prev, pager, next"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </el-card>

  </div>
</template>

<script lang="tsx" setup>
import { computed, onBeforeMount, reactive, ref } from 'vue';
import { QueryForm, QueryFormItem } from '@/components/query-form';
import useLoading from '@/hooks/use-loading';
import TableColumn, { TableColumnData } from '@/components/table-column/index.vue';
import TableToolbar from '@/components/table-toolbar/index.vue';
import useTableSelection from '@/hooks/use-table-selection';
import { TableInstance } from 'element-plus';
import useTable from '@/hooks/use-table.ts';
import { pickerShortcuts } from '@/utils';
import { QueryFormItemRule } from '@/components/query-form/constants.ts';
import { userLoginLogList } from '@/api/api-user.ts';
import dayjs from 'dayjs';
import { UserInfoLink } from '@/components/user-info-link';

defineOptions({name: 'user-login-log'});

// 查询
const queryFormData = reactive({
  user_id: undefined,
  account: undefined,
  device_no: undefined,
  ip_address: undefined,
  // 时间范围 格式 2023-01-01~2023-01-31
  date: undefined,
});
const queryFormRef = ref<InstanceType<typeof QueryForm>>();
const queryFormItems = ref<QueryFormItemRule[]>([
  {type: 'input', prop: 'user_id', label: '用户编号', placeholder: '请输入用户编号', clearable: true},
  {type: 'input', prop: 'account', label: '用户账号', placeholder: '请输入用户账号', clearable: true,},
  {type: 'input', prop: 'device_no', label: '设备号', placeholder: '请输入设备号', clearable: true,},
  {type: 'input', prop: 'ip_address', label: '登录地址', placeholder: '请输入登录地址', clearable: true,},
]);

// 列表数据
const tableRef = ref<TableInstance>();
const tableData = ref<any[]>([]);
const totalCount = ref(0);
const pickerDate = ref<any[]>([]);

// 操作区域宽度计算
const operateWidth = computed(() => {
  return 0;
});

// 列设置
const columns = ref<TableColumnData[]>([
  {prop: 'id', label: '编号', width: 110, align: 'center', sortable: 'custom'},
  {prop: 'user_id', label: '用户编号', width: 110, align: 'center', sortable: 'custom'},
  {prop: 'account', label: '用户账号', minWidth: 160, align: 'right', sortable: 'custom'},
  {prop: 'device_no', label: '设备号', minWidth: 288, align: 'right', sortable: 'custom'},
  {prop: 'ip_address', label: '登录地址', minWidth: 145, align: 'right', sortable: 'custom'},
  {prop: 'platform', label: '平台类型', minWidth: 120, align: 'right', sortable: 'custom'},
  {prop: 'device_model', label: '手机型号', minWidth: 120, align: 'right', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'device_product', label: '手机品牌', minWidth: 120, align: 'right', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'version', label: '应用版本', minWidth: 120, align: 'right', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'create_time', label: '登录时间', width: 180, align: 'center', sortable: 'custom'},
]);

onBeforeMount(() => {
  if (operateWidth.value > 0) {
    columns.value.push({prop: 'operations', label: '操作', fixed: 'right', width: operateWidth.value, align: 'center', headerAlign: 'center'},)
  }
  // 重置查询表单
  handleResetQueryForm();
});

const [loading, setLoading] = useLoading(false);
const {tableMethods, tableState} = useTable(() => fetchDataList(), queryFormRef, true, true);
const {size, stripe, showQueryForm, pageQuery, pageSizes} = tableState;
const {handleSizeChange, handleCurrentChange, handleSortChange, handleResetForm} = tableMethods;
const {handleSelectChange, handleSelectAll, multipleSelection, clearSelection} = useTableSelection(tableData, tableRef);

// 数据查询
const fetchDataList = async () => {
  setLoading(true);
  try {
    // 时间范围参数
    // @ts-ignore
    queryFormData.date = pickerDate.value && pickerDate.value.length == 2 ? pickerDate.value[0] + '~' + pickerDate.value[1] : undefined
    // 查询数据
    const {data} = await userLoginLogList({
      page_num: pageQuery.pageNum,
      page_size: pageQuery.pageSize,
      order_mode: pageQuery.orderMode,
      order_column: pageQuery.orderColumn,
      ...queryFormData,
    });
    // 结果转换
    tableData.value = data.list;
    totalCount.value = data.pages.total_count;
  } catch (err) {
  } finally {
    setLoading(false);
  }
};

// 刷新数据
const handleSearch = () => {
  fetchDataList();
};

// 重置查询条件
const handleResetQueryForm = () => {
  let nowDate = new Date();
  let endTime = dayjs(nowDate).format('YYYY-MM-DD');
  let startTime = dayjs(nowDate.setDate(nowDate.getDate() - 7)).format('YYYY-MM-DD');
  pickerDate.value = [startTime, endTime];
  clearSelection();
  handleResetForm();
};
</script>

<style lang="scss" scoped>

</style>
